
using Manon.Admin.ApplicationCore.Common;
using Manon.Admin.ApplicationCore.Infrastructure;
using Manon.Admin.Web.Common;
using Manon.Core.IOC;
using Manon.Core.Commons;
using Manon.Core.Filters;
using Manon.Repository;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Text;
using Microsoft.Extensions.Logging;

namespace Manon.Admin.Web
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }
         
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews(options =>
            {
                options.Filters.Add<ApiResultFilter>();
                options.Filters.Add<ApiActionFilter>(); 
                options.Filters.Add<ApiExceptionAsyncFilter>();
            })
           .ConfigureApiBehaviorOptions(options =>
           {
               options.SuppressModelStateInvalidFilter = true;
           })
           .AddRazorRuntimeCompilation()
           .AddJsonOptions(options =>
           {
               options.JsonSerializerOptions.Converters.Add(new DateTimeConverter());
           });

            services.AddAuthentication(options =>
            {

                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(jwtOptions =>
            {
                jwtOptions.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters()
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(AppSettings.SecretKey)),
                    ValidIssuer = AppSettings.Issuer,
                    ValidAudience = AppSettings.Audience,
                    ValidateIssuer = true,
                    ValidateAudience = true,
                    ValidateLifetime = true,
                    ClockSkew = TimeSpan.Zero

                }; 
            });

            services.AddUnitOfWorkService<AdminDbContext>(options =>
            {
                options.UseMySql(Configuration.GetSection("ConnectionString")?.Value, new MySqlServerVersion(new Version(8, 0, 16)));
            });


            services.AddTransient<IIdentityUser, IdentityUser>();
            services.AddHttpContextAccessor();
            services.AddServices("Manon.Admin.Web");
              
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {  
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error"); 
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthentication();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}
